package com.example.demo.config.socket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

//webSocket 定时器
@Component
public class WebSocketScheduler implements CommandLineRunner {

    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    private ScheduledExecutorService scheduler;

    @Override
    public void run(String... args) {
        // 定义定时任务
        Runnable messagePusher = () -> {
            // 生成要推送的消息
            String message = "Server time: " + System.currentTimeMillis();
            // 广播消息
            myWebSocketHandler.broadcastMessage(message);
        };

        // 创建调度器
        scheduler = Executors.newSingleThreadScheduledExecutor();
        // 每 5 秒执行一次任务
        scheduler.scheduleAtFixedRate(messagePusher, 0, 30, TimeUnit.SECONDS);
    }

    // 在应用关闭时关闭调度器
    public void shutdown() {
        if (scheduler != null) {
            scheduler.shutdown();
        }
    }
}
